package vip.zhenzicheng.kafka.kafka;

import com.alibaba.fastjson2.JSON;
import com.zzc.zfast.web.domain.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.zhenzicheng.kafka.properties.KafkaTopicProperties;
import vip.zhenzicheng.kafka.vo.TestVO;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;


/**
 * 生产者
 *
 * @author zhenzicheng
 * @date 2022-09-27 18:33
 */
@RequestMapping("/producer")
@RestController
@Tag(name = "Kafka消息生产者", description = "消息发送测试")
public class KafkaController {

  @Autowired
  private KafkaTemplate<String, String> kafkaTemplate;

  @Autowired
  private KafkaTopicProperties topicProperties;

  @Operation(description = "简单发送")
  @PostMapping("/send")
  public Result<String> send(TestVO vo) throws ExecutionException, InterruptedException, TimeoutException {
    ListenableFuture<SendResult<String, String>> lf = kafkaTemplate.send(topicProperties.getMyTest(), JSON.toJSONString(vo));
    // 获取发送返回值，最多等待10s
    SendResult<String, String> sendResult = lf.get(10, TimeUnit.SECONDS);
    String value = sendResult.getProducerRecord().value();
    return Result.dataOf(value);
  }


}
